﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
using System.Threading;
using System.Text.RegularExpressions;

public partial class BG_Manage_BG_CE_IMG : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {

        }
    }


    protected void Download_IMG()
    {
        Regex re = new Regex(@"src\s*=\s*(?:([""'])(?<src>[^""']+)\1|(?<src>[^\s>]+))", RegexOptions.IgnoreCase | RegexOptions.Singleline);
        MatchCollection mc = re.Matches(this.Editor1.XHTML.ToString());
        foreach (Match m in mc)
        {
            string url = m.Groups["src"].Value;
            string filepath = url;
            DateTime now = DateTime.Now; //获取系统时间
            
            //
            string CreatePathYear = System.Web.HttpContext.Current.Server.MapPath("../Uploads/CE_IMG/" + DateTime.Now.ToString("yyyy")).ToString();
            string CreatePathMD = System.Web.HttpContext.Current.Server.MapPath("../Uploads/CE_IMG/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MMdd")).ToString();

            //如果以年命名的文件夹没有，则建立以年为文件名的文件
            if (!Directory.Exists(CreatePathYear))
            {
                Directory.CreateDirectory(CreatePathYear);
            }
            //如果以月日命名的文件夹没有，则建立以为月日文件名的文件
            if (!Directory.Exists(CreatePathMD))
            {
                Directory.CreateDirectory(CreatePathMD);
            }
            //下面对Editor中的图片进行操作
            if (url.Substring(0, 7).ToLower() == "http://")
            {

                string extension = "." + url.Substring(url.LastIndexOf(".") + 1);           //扩展名
                string path = HttpContext.Current.Server.MapPath("../Uploads/CE_IMG/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MMdd")+"/" );     //路径
                string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + extension;      //文件名
                path = path + filename;
                filepath = "../Uploads/CE_IMG/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("MMdd") + "/" + filename;
                WebClient myWebClient = new WebClient();
                myWebClient.DownloadFile(url, path);
                this.Editor1.Text = this.Editor1.XHTML.ToString().Replace(url, filepath);
                Thread.Sleep(800);

            }
            //Pic.Items.Add(new ListItem(filepath, filepath)); 

        }
    }



    protected void Button1_Click(object sender, EventArgs e)
    {
        Download_IMG();

        this.Label1.Text = this.Editor1.Text;
    }
}
